package com.app.controller;


import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.app.mapper.GasDetailsMapper;
import com.app.pojo.GasDetails;
import com.app.pojo.RequestLogs;
import com.app.service.IRequestLogsService;
import com.app.util.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;

/**
 * <p>
 * 请求日志记录表 前端控制器
 * </p>
 *
 * @author yoominic
 * @since 2024-08-01
 */
@RestController
@RequestMapping("/requestLogs")
public class RequestLogsController {

    @Value("${gas.api.url}")
    private String GAS_API_URL;
    @Value("${gas.api.key}")
    private String GAS_API_KEY;

    @Autowired
    private IRequestLogsService requestLogsService;

    @Autowired
    private GasDetailsMapper gasDetailsMapper;

    @Autowired
    private Md5Util md5Util;



    //给燃气平台推送
    @GetMapping("/pushGasRequest")
    public Result pushGasRequest(String field,String meterno,String value) {
        JSONObject object = requestLogsService.pushGasRequestLogs(field,meterno,value);
        return Result.success(object);
    }


    // 接收燃气推送日志
    @PostMapping("/receiveGasRequest")
    public JSONObject receiveGasRequest(@RequestBody JSONObject jonstr, HttpServletRequest request) {
        String ip = IpUtil.getIpAddress(request);
        JSONObject response_object = requestLogsService.receiveGasRequestLogs(jonstr, ip);
        return response_object;
    }

    /**
     * 给燃气发请求，查余额
     *  field 指令
     * @param meterno 户号（account）
     *  value 推送的数据或""
     * @return
     */
    @GetMapping("/checkBalance")
    public BigDecimal checkBalance(String meterno) {
        return  requestLogsService.checkBalance(meterno);
    }

//    /**
//     * 为负account再给燃气推送关闸指令
//     * @return
//     */
//    @PostMapping("/gate")
//    JSONObject gate(String field,String meterno,String value){
//
//    }

    /**
     * 发指令查余额  数据库同步余额 欠费的在执行关闸指令
     */
    @Async
    @Scheduled(cron =" 0 0 0 * * *")//每天凌晨执行一次
    @Scheduled(cron = "*/10 * * * * *")//每十秒执行一次
    public  void   checkTheBalanceAndCloseTheGate(){
        //查所有的户号

        //循环发指令查余额

        //拿到余额统一记录并在记录欠费的户号 更新数据库

        //统一发请求给欠费的   进行关闸

    }


}

